package cn.edu.neusoft.demo.hospital2.Controller;

import cn.edu.neusoft.demo.hospital2.Dao.DoctorWorkDao;
import cn.edu.neusoft.demo.hospital2.Dao.WorkPlanDao;
import cn.edu.neusoft.demo.hospital2.pojo.DoctorWork;
import cn.edu.neusoft.demo.hospital2.pojo.DoctorWorkParameter;
import cn.edu.neusoft.demo.hospital2.pojo.FullDoctorWork;
import cn.edu.neusoft.demo.hospital2.pojo.WorkPlan;
import cn.edu.neusoft.demo.hospital2.Service.WorkPlanService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.edu.neusoft.demo.hospital2.common.Result;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@CrossOrigin(origins = "*")
@Tag(name = "WorkPlanController相关的api")
@RequestMapping("/workPlan")
public class WorkPlanController {
    @Autowired
    private WorkPlanService workPlanService; // 使用接口注入
    @Autowired
    private WorkPlanDao workPlanDao;
    @Autowired
    private DoctorWorkDao doctorWorkDao;

    /*
     * 周一到周日的计划大纲
     * */
    @Operation(summary = "放入一周的日期字符串参数来获取周计划",description = "放入一周的日期字符串参数来获取周计划")
    @RequestMapping(value = "/getPlansByWeek",method = RequestMethod.GET)
    public Result getPlansByWeek(String week){
        System.out.println(week);
        List<DoctorWork> list=workPlanDao.getWorkPlanByWeek(week);
        return Result.ok(list);
    }

    /*
     * 周一到周日的计划大纲
     * */
    @Operation(summary = "传入起始日期字符串来获取周计划",description = "传入起始日期字符串来获取周计划")
    @RequestMapping(value = "/getPlansStatus2",method = RequestMethod.GET)
    public Result getPlansStatus2(String startDay){
        Date d=this.getDate(startDay);
        WorkPlan wp=workPlanService.getPlansStatus(d);

        return Result.ok(wp);
    }

    /*
     * 周一到周日的计划大纲
     * */
    @Operation(summary = "传入起始日期字符串来获取周计划",description = "传入起始日期字符串来获取周计划")
    @RequestMapping(value = "/getPlansStatus",method = RequestMethod.GET)
    public WorkPlan getPlansStatus(String startDay){
        System.out.println("=========="+startDay);
        Date d=this.getDate(startDay);
        return workPlanService.getPlansStatus(d);
    }

    /*
     * 生成周一到周日的计划大纲
     * */
    @Operation(summary = "生成周计划",description = "生成周计划")
    @RequestMapping(value = "/generatePlans",method = RequestMethod.POST)
    public Result generatePlans(String startDay){
        WorkPlan wp=new WorkPlan();
        wp.setDay(startDay);
        wp.setStatus(0);//初始状态
        wp.setCreateBy("admin");
        wp.setWeekday("1");

        boolean res=workPlanService.generatePlan(wp);
        if(res)
            return Result.ok("生成成功");
        else
            return Result.fail("生成失败");
    }

    /*
     * 修改计划大纲的状态
     * */
    @Operation(summary = "修改计划大纲的状态",description = "修改计划大纲的状态")
    @RequestMapping(value = "/updatePlanStatus",method = RequestMethod.PUT)
    public Result updatePlanStatus(String day,int status){
        System.out.println(day);
        System.out.println(status);
        Date d=this.getDate(day);
        WorkPlan wp=new WorkPlan();
        wp.setDay(d.toString());
        wp.setStatus(status);//初始状态
        int res=workPlanService.updateByDay(wp);
        if(res>0)
            return Result.ok("状态修改成功");
        else
            return Result.fail("状态修改失败");
    }

    /*
     * 获取当前周的所有医生排班情况
     * */
    @Operation(summary = "获取当前周的所有医生排班情况",description = "获取当前周的所有医生排班情况")
    @RequestMapping(value = "/getDoctorWorks",method = RequestMethod.GET)
    public Result getDoctorWorks(String day){
        List<FullDoctorWork> list=workPlanService.getAllBaseInfo(day);
        return Result.ok(list);
    }

    @Operation(summary = "修改医生排班信息",description = "修改医生排班信息")
    @RequestMapping(value = "/updateDoctorWorks",method = RequestMethod.POST)
    public Result updateDoctorWorks(@RequestParam String day,@RequestParam int departmentId,@RequestBody DoctorWorkParameter parameter){
        List<DoctorWork> doctors=parameter.getDoctorworks();
        System.out.println(doctors.toString());
        Date d=this.getDate(day);
        int year=1900+d.getYear();
        int month=1+d.getMonth();
        int date=d.getDate();
        System.out.println(year);
        System.out.println(month);
        System.out.println(date);
        WorkPlan wp=this.workPlanDao.selectByDay(year, month, date);
//		System.out.println(year+"-0"+month+"-"+date);
//		WorkPlan wp=workPlanMapper.selectByDay(year+"-0"+month+"-"+date);
        int res=0;
        for(DoctorWork doctor:doctors){
            if(doctor.getDepartId1()==departmentId)
            {

                QueryWrapper<DoctorWork> wrapper = new QueryWrapper<DoctorWork>();
                wrapper.eq("day", day);
                wrapper.eq("doc_id", doctor.getDocId());
                doctorWorkDao.deleteUsingWrapper(wrapper);
                doctor.setDay(day);
                doctor.setWeekday(wp.getWeekday());
                doctor.setFeeId(doctor.getFeeId());
                int countLeft=0;
                if(doctor.getAmwork()!=null&&!doctor.getAmwork().equals("0"))
                    countLeft+=30;
                if(doctor.getPmwork()!=null&&!doctor.getPmwork().equals("0"))
                    countLeft+=30;
                doctor.setCountLeft(countLeft);//设置可挂号数量
                doctorWorkDao.insert(doctor);
                res++;
            }
        }
        if(res>0)
            return Result.ok("保存成功");
        else
            return Result.fail("保存失败");
    }

    /**
     * 字符串转换成时间类型
     * @param str
     * @return
     */
    public Date getDate(String str) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = dateFormat.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    // 查询所有工作计划
    @GetMapping("/getAllWorkPlans")
    public List<WorkPlan> getAllWorkPlans() {
        return workPlanService.getAllWorkPlans();
    }

    // 根据日期查询工作计划
    @GetMapping("/getWorkPlanByDay")
    public WorkPlan getWorkPlanByDay(String day) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date utilDate = sdf.parse(day);
            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

            return workPlanService.getWorkPlanByDay(sqlDate);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("日期格式必须为 yyyy-MM-dd", e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    // 新增工作计划
    @PostMapping("/addWorkPlan")
    public boolean addWorkPlan(@RequestBody WorkPlan workPlan) {
        return workPlanService.addWorkPlan(workPlan);
    }

    // 修改工作计划
    @PutMapping("/updateWorkPlan")
    public boolean updateWorkPlan(@RequestBody WorkPlan workPlan) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false);
            sdf.parse(workPlan.getDay().toString());

            return workPlanService.updateWorkPlan(workPlan);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid date format for day. Expected format: yyyy-MM-dd", e);
        }
    }

    // 删除工作计划
    @GetMapping("/deleteWorkPlan")
    public Result deleteWorkPlan(String day) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date utilDate = sdf.parse(day);
            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

            workPlanService.deleteWorkPlan(sqlDate);
            return Result.ok("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("删除失败");
        }
    }
}
